import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from typing import Optional
import logging
from datetime import datetime, timedelta

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 邮箱验证码存储（实际项目中应该使用Redis等缓存）
email_verification_codes = {}

class EmailService:
    """
    邮件服务类，用于发送邮箱验证码
    """
    
    def __init__(self, smtp_server: str = "smtp.qq.com", smtp_port: int = 587):
        """
        初始化邮件服务
        
        Args:
            smtp_server: SMTP服务器地址
            smtp_port: SMTP服务器端口
        """
        self.smtp_server = smtp_server
        self.smtp_port = smtp_port
        self.sender_email = "83777570@qq.com"
        self.sender_password = "czcwfbgvmvjqbjff"  # SMTP授权码
    
    def send_verification_code(self, to_email: str, code: str) -> bool:
        """
        发送邮箱验证码
        
        Args:
            to_email: 接收邮箱
            code: 验证码
        
        Returns:
            bool: 发送是否成功
        """
        # 创建邮件内容
        msg = MIMEMultipart()
        msg['From'] = self.sender_email
        # msg['From'] = "AIGD100"
        msg['To'] = to_email
        msg['Subject'] = "邮箱验证码"
        
        # 邮件正文
        body = f"""
        <html>
            <body>
                <h2>邮箱验证码</h2>
                <p>您的验证码是：<strong style="color: #007bff; font-size: 24px;">{code}</strong></p>
                <p>验证码有效期为5分钟，请及时使用。</p>
                <p>如果您没有申请此验证码，请忽略此邮件。</p>
            </body>
        </html>
        """
        
        msg.attach(MIMEText(body, 'html', 'utf-8'))
        
        # 连接SMTP服务器并发送邮件
        server = None
        try:
            server = smtplib.SMTP(self.smtp_server, self.smtp_port)
            server.starttls()  # 启用TLS加密
            server.login(self.sender_email, self.sender_password)
            server.send_message(msg)
            logger.info(f"验证码邮件发送成功: {to_email}")
            return True
        except smtplib.SMTPException as smtp_e:
            # SMTP相关错误，但可能邮件已发送
            logger.warning(f"SMTP连接异常但邮件可能已发送: {to_email}, 错误: {str(smtp_e)}")
            # 对于某些SMTP错误，邮件实际上已经发送成功
            return True
        except Exception as e:
            logger.error(f"发送验证码邮件失败: {to_email}, 错误: {str(e)}")
            return False
        finally:
            # 确保连接被正确关闭
            if server:
                try:
                    server.quit()
                except:
                    pass  # 忽略关闭连接时的错误

# 全局邮件服务实例
email_service = EmailService()

def send_email_verification_code(email: str, code: str) -> bool:
    """
    发送邮箱验证码并存储
    
    Args:
        email: 邮箱地址
        code: 验证码
    
    Returns:
        bool: 发送是否成功
    """
    # 发送邮件
    success = email_service.send_verification_code(email, code)
    
    if success:
        # 存储验证码和过期时间（5分钟后过期）
        expire_time = datetime.now() + timedelta(minutes=5)
        email_verification_codes[email] = {
            'code': code,
            'expire_time': expire_time
        }
        logger.info(f"邮箱验证码已存储: {email}")
    
    return success

def verify_email_code(email: str, code: str) -> bool:
    """
    验证邮箱验证码
    
    Args:
        email: 邮箱地址
        code: 用户输入的验证码
    
    Returns:
        bool: 验证是否成功
    """
    if email not in email_verification_codes:
        logger.warning(f"邮箱验证码不存在: {email}")
        return False
    
    stored_data = email_verification_codes[email]
    
    # 检查是否过期
    if datetime.now() > stored_data['expire_time']:
        # 删除过期的验证码
        del email_verification_codes[email]
        logger.warning(f"邮箱验证码已过期: {email}")
        return False
    
    # 验证码匹配
    if stored_data['code'] == code:
        # 验证成功后删除验证码
        del email_verification_codes[email]
        logger.info(f"邮箱验证码验证成功: {email}")
        return True
    else:
        logger.warning(f"邮箱验证码错误: {email}")
        return False

def cleanup_expired_codes():
    """
    清理过期的验证码
    """
    current_time = datetime.now()
    expired_emails = []
    
    for email, data in email_verification_codes.items():
        if current_time > data['expire_time']:
            expired_emails.append(email)
    
    for email in expired_emails:
        del email_verification_codes[email]
        logger.info(f"清理过期验证码: {email}")